<?php

namespace App\Models;

use Session;
use Cookie;

class Member extends BaseModel
{
    protected $table = "member";

    const PREFIX = 'mid_';


    public function __construct()
    {
        parent::__construct();
        $this->fields = ['id', 'wxname', 'wxavatar', 'cardnum','openid','invit', 'reffer','fd', 'rid', 'role', 'status', 'point', 'piao'];
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function login($request)
    {
        if (!$request['username'] || !$request['pwd']) {
            return ['status' => -1];
        }
        $data['status'] = 1;
        $where['username'] = $request['username'];
        $where['pwd'] = md5($request['pwd']);
        $member = $this->getOne($where);
        if (!$member) {
            $data['status'] = 0;
            return $data;
        }
        $key = self::PREFIX . $member['id'];
        $member = $member->toArray();
        $this->memcache->set($key, $member);
        $data['token'] = md5($member['openid'] . '_' . $member['id']);
        $data['mid'] = $member['id'];
        return $data;
    }

    public function addMember($wxInfo)
    {
        $data['openid'] = $wxInfo['openid'];
        $data['wxname'] = $wxInfo['nickname'];
        $data['wxavatar'] = $wxInfo['headimgurl'];
        $data['cardnum'] = 8;
        $data['ip'] = request()->ip();
        $data['last_login_time'] = time();
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $res = $this->add($data);
        if (!$res) {
            return false;
        }
        return $res;
    }

    public function findMember($openid)
    {
        $where['openid'] = $openid;
        $member = $this->getOne($where);
        if ($member) {
            $member = $member->toArray();
        }
        return $member;
    }

    public function getMemberInfo($mid)
    {
        $member = $this->getOne(['id' => $mid]);
        if ($member) {
            $member = $member->toArray();
            if ($member['rid'] && $member['status'] != 0) {
                $room = new Room();
                $roomInfo = $room->readRoomCache($member['rid']);
                if (!$roomInfo || !in_array($member['id'],$roomInfo['players'])) {
                    $member['status'] = 0;
                    $member['rid'] = 0;
                    $member['role'] = '';
                    $member['fd'] = 0;
                    $this->resetMemberInfo($mid);
                }
            }
            if (!$member['invit']) {
                $data['invit'] = getRandNum(6);
                $this->up(['id' => $mid],$data);
                $member['invit'] = $data['invit'];
            }
        }
        return $member;
    }


    public function getMember($mid)
    {
        $key = self::PREFIX . $mid;
        $member = $this->memcache->get($key);
        if (!$member) {
            $member = $this->getOne(['id' => $mid]);
            if ($member) {
                $member = $member->toArray();
            }
            $this->memcache->set($key, $member);
        }
        return $member;
    }

    public function setMember($mid, $data = '')
    {
        $key = self::PREFIX . $mid;
        $where['id'] = $mid;
        if ($data) {
            $this->up($where, $data);
        }
        $member = $this->getOne(['id' => $mid]);
        if ($member) {
            $member = $member->toArray();
        }
        $this->memcache->set($key, $member);
        return $member;
    }

    public function delCache($mid)
    {
        $key = self::PREFIX . $mid;
        $this->memcache->delete($key);
    }


    public function wechatLogin($wxInfo)
    {
        $data['status'] = 1;
        $openid = $wxInfo['openid'];
        $member = $this->findMember($openid);
        $mid = '';
        if (!$member) {
            if ($wxInfo) {
                $mid = $this->addMember($wxInfo);
            }
        } else {
            $mid = $member['id'];
        }
        $memberData['openid'] = $openid;
        $memberData['last_login_time'] = time();
        if (isset($wxInfo['ip'])) {
            $memberData['ip'] = request()->ip();
        }
        $memberData['updated_at'] = date('Y-m-d H:i:s',time());
        $this->setMember($mid,$memberData);
        $token = md5($openid . '_' . $mid);
        $url = url('').'/dist/index.blade.php#/newRoom?mid='.$mid.'&token='.$token;
        Header("Location: $url");
    }

    public function addCard($member, $alogid, $num, $type)
    {
        $this->start();
        try {
            $data['cardnum'] = $member['cardnum'] + $num;
            $where['id'] = $member['id'];
            $this->up($where, $data);
            $this->delCache($member['id']);
            $memberCardLog = new MemberCardLog();
            $memberCardLog->addLog($alogid, $member, $num, $type);
            $this->commit();
            $this->delCache($member['id']);
            return true;
        } catch (\Exception $e) {
            $this->rollBack();
            return false;
        }
    }

    public function saveRoleStatus($fd, $rid, $mid, $role, $status, $piao)
    {
        $where['id'] = $mid;
        $data['fd'] = $fd;
        $data['rid'] = $rid;
        $data['role'] = $role;
        $data['status'] = $status;
        $data['piao'] = $piao;
    }

    public function offLine($fd)
    {
        $where['fd'] = $fd;
        $member = $this->getOne($where);
        $room = new Room();
        $roomData = $room->getRoomInfo($member['rid']);
        if (isset($roomData['num'])) {
            $roomData['num'] -= 1;
        } else {
            $roomData['num'] = 0;
        }
        $room->resetRoomInfo($member['rid'], $roomData);
        $data['status'] = -1;
        $data['fd'] = 0;
        $this->up($where, $data);
        $this->delCache($member['id']);
        $backData['rid'] = $member['rid'];
        $backData['mid'] = $member['id'];
        $backData['role'] = $member['role'];
        $backData['type'] = -1;
        $backData['num'] = $roomData['num'];
        return $backData;
    }

    public function resetMemberInfo($id)
    {
        $member = $this->getMember($id);
        $room = new Room();
        $info = $room->getRoomInfo($member['rid']);
        unset($info[$member['role']]);
        unset($info['players'][$member['role']]);
        if (isset($info['num'])) {
            if ($info['num'] > 0) {
                $info['num'] -= 1;
            }
        }
        if (isset($info['players']) && !count($info['players'])) {
            $room->clearRoomInfo($member['rid']);
        } else {
            $room->resetRoomInfo($member['rid'],$info);
        }
        $where['id'] = $id;
        $data['role'] = '';
        $data['rid'] = 0;
        $data['fd'] = 0;
        $data['piao'] = 0;
        $data['status'] = 0;
        $this->up($where, $data);
        $this->delCache($id);
    }

    public function invite($request)
    {
        $mid = $request['mid'];
        $code = $request['code'];
        $result['status'] = 0;
        if (!($mid && $code)) {
            $result['msg'] = '请输入邀请码';
        }
        $member = $this->getOne(['id'=>$mid]);
        if ($member['reffer']) {
            $result['msg'] = '您已绑定领取，无法再次进行领取';
            return $result;
        }
        $condition['invit'] = $code;
        $condition['id'] = ['<>',$mid];
        $res = $this->getOne($condition);
        if (!$res) {
            $result['msg'] = '该邀请码不存在';
            return  $result;
        }
        $this->start();
        try {
            $where['id'] = $mid;
            $data['reffer'] = $res['id'];
            $data['reffer_name'] = $res['wxname'];
            $data['reffer_time'] = date('Y-m-d H:i:s', time());
            $data['cardnum'] = $member['cardnum']+1;
            $this->up($where, $data);
            $where1['id'] = $res['id'];
            $data1['cardnum'] = $res['cardnum']+1;
            $this->up($where1, $data1);
            $this->commit();
            $result['status'] = 1;
            $result['msg'] = '领取成功';
            $this->delCache($mid);
        } catch (\Exception $e) {
            $this->rollBack();
            $result['msg'] = '领取失败';
        }
        return $result;
    }

    public function getFunList($request)
    {
        $mid = $request['mid'];
        $where['reffer'] = $mid;
        $res = $this->getList($where,'*',['id'=>'desc'],5);
        if ($res) {
            $res = $res->toArray();
        }
        return $res;
    }



}